package com.auth.config.details;

import com.auth.config.exception.ExceptionInstance;
import com.auth.system.entity.build.SystemUserEntity;
import com.auth.system.entity.dto.SystemRoleDto;
import com.auth.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: hw
 * @date: 2020/11/27 15:18
 */
@Slf4j
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUserEntity user = userService.getUser(username);
        ExceptionInstance.protectionPassword(null == user, "用户名或密码错误");
        List<SystemRoleDto> roles = userService.getRole(username);
        Set<GrantedAuthority> authorities = new HashSet<>();
        roles.forEach(role ->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(role.getPermissionLabel());
            authorities.add(simpleGrantedAuthority);
        });

        return new User(user.getUserName(), user.getPassword(),user.getIsEnable() != 1,!user.getIsDelete().equals("1"),true,true,authorities);
    }
}
